package com.zrh.jsd.service.studydemo.common_thread;

import java.util.concurrent.atomic.AtomicInteger;

public class Test {
    private static long count = 0;
    private static Object lock;

    public static void main(String[] args) throws InterruptedException {
        System.out.println(calc());
    }

    //可以给add10K增加synchronized保证得到正确的结果。
    private void add10K() {
        int idx = 0;
        synchronized ((Object) count) {
            while (idx++ < 10000) {
                count += 1;
            }
        }
        synchronized (lock) {
            while (idx++ < 10000) {
                count += 1;
            }
        }
    }

    public static long calc() throws InterruptedException {
        final Test test = new Test();
        // 创建两个线程，执行 add() 操作
        Thread th1 = new Thread(() -> {
            test.add10K();
        });
        Thread th2 = new Thread(() -> {
            test.add10K();
        });
        // 启动两个线程
        th1.start();
        th2.start();
        // 等待两个线程执行结束
        th1.join();
        th2.join();
        return count;
    }
}